package com.zwp.base.binding

import android.util.Log
import androidx.databinding.BindingAdapter
import androidx.databinding.BindingMethod
import androidx.databinding.BindingMethods
import androidx.lifecycle.findViewTreeLifecycleOwner
import androidx.paging.LoadStateAdapter
import androidx.paging.PagingData
import androidx.recyclerview.widget.RecyclerView
import com.zwp.base.paging.BindingRecyclerViewAdapter
import com.zwp.base.paging.CommonFooterAdapter
import me.tatarka.bindingcollectionadapter2.ItemBinding

@BindingMethods(
    BindingMethod(type = RecyclerView::class, attribute = "itemBinding", method = "setAdapter"),
    BindingMethod(type = RecyclerView::class, attribute = "adapter", method = "setAdapter"),
    BindingMethod(type = RecyclerView::class, attribute = "footeradapter", method = "setAdapter"),
)
class RecyclerAdapter

@BindingAdapter(value = ["itemBinding", "adapter", "footeradapter"], requireAll = false)
fun <T : Any, VH : RecyclerView.ViewHolder> RecyclerView.setAdapter(
    itemBinding: ItemBinding<T>?,
    adapter: BindingRecyclerViewAdapter<T>?,
    footerAdapter: LoadStateAdapter<VH>?,
) {
    var newAdapter = adapter
    val oldAdapter = this.adapter as? BindingRecyclerViewAdapter<T>
    require(newAdapter != null || oldAdapter != null) {
        "adapter can't find"
    }
    if (newAdapter == null) {
        newAdapter = oldAdapter
    }
    newAdapter?.let {
        it.itemBinding = itemBinding
    }

    if (oldAdapter !== newAdapter) {
        if (footerAdapter != null) {
            this.adapter = newAdapter?.withLoadStateFooter(footerAdapter)
        } else {
            this.adapter = newAdapter
        }
    }
}